<template>
  <div class="box">
    <el-card shadow="never">
      <div class="content">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-position="labelPosition"
          label-width="110px"
        >
          <el-form-item label="优惠券类型：">
            <el-select class="m-2" v-model="form.type" placeholder="请选择">
              <el-option
                v-for="item in option"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优惠券名称：" prop="name"
            ><el-input style="width: 50%" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="适用平台："
            ><el-select
              class="m-2"
              v-model="form.platform"
              placeholder="请选择"
            >
              <el-option
                v-for="item in platformSelect"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="总发行量：" prop="publishCount"
            ><el-input
              style="width: 50%"
              v-model="form.publishCount"
              placeholder="只能输入正整数"
            ></el-input>
          </el-form-item>
          <el-form-item label="面额：" prop="amount"
            ><el-input
              style="width: 50%"
              v-model="form.amount"
              placeholder="面值只能是数值，限2位小数"
            >
              <template #append>
                <el-button>元</el-button>
              </template></el-input
            >
          </el-form-item>
          <el-form-item label="每人限领：" prop="perLimit">
            <el-input
              style="width: 50%"
              v-model="form.perLimit"
              placeholder="只能输入正整数"
            >
              <template #append>
                <el-button>张</el-button>
              </template></el-input
            ></el-form-item
          >
          <el-form-item label="使用门槛：" porp="minPoint">
            <el-input
              style="width: 50%"
              v-model="form.minPoint"
              placeholder="只能输入正整数"
            >
              <template #prepend>
                <el-button>满</el-button>
              </template>
              <template #append>
                <el-button>元可用</el-button>
              </template></el-input
            >
          </el-form-item>
          <el-form-item label="领取日期" prop="enableTime">
            <ElConfigProvider :locale="zhCn">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.enableTime"
                style="width: 50%"
            /></ElConfigProvider>
          </el-form-item>
          <el-form-item label="有效期" prop="enableTime">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.startTime"
              style="width: 40%"
            /><span style="margin: 0 5px">至</span>
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="form.endTime"
              style="width: 50%"
            />
          </el-form-item>
          <el-form-item label="可使用商品：">
            <el-radio-group v-model="type" @change="choseUseType">
              <el-radio-button label="全场通用" />
              <el-radio-button label="指定分类" />
              <el-radio-button label="指定商品" />
            </el-radio-group>
          </el-form-item>
          <div v-show="type === '指定分类'">
            <el-form-item label="">
              <el-cascader
                v-model="value"
                :options="categoryList"
                @change="handleChange"
                ref="refSubCat"
              >
              </el-cascader>
              <el-button @click="addType">添加</el-button>
              <el-table
                :data="userList"
                border
                style="width: 100%; margin-top: 5px"
              >
                <el-table-column prop="name" label="分类名称" width="400"
                  ><template #default="{ row }">
                    <span
                      >{{ row.parentCategoryName }}>{{
                        row.productCategoryName
                      }}</span
                    >
                  </template></el-table-column
                >
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <el-button
                      text
                      type="primary"
                      size="small"
                      @click="delCategory(row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
          <div v-show="type === '指定商品'">
            <el-form-item label="">
              <el-select
                v-model="value"
                filterable
                remote
                reserve-keyword
                placeholder="商品名称/商品货号"
                :remote-method="remoteMethod"
                :loading="loading"
                @change="handleSelectBranchCom"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="{
                    value: item.value,
                    label: item.label,
                    productSn: item.productSn,
                  }"
                  ><span style="float: left">{{ item.label }}</span>
                  <span class="pro">NO.{{ item.productSn }}</span>
                </el-option>
              </el-select>
              <el-button @click="addShop">添加</el-button>
              <el-table
                :data="shopList"
                border
                style="width: 100%; margin-top: 5px"
              >
                <el-table-column prop="name" label="商品名称" width="300">
                  <template #default="{ row }">
                    <span>{{ row.productName }}</span>
                  </template></el-table-column
                >
                <el-table-column prop="productSn" label="货号" width="100">
                  <template #default="{ row }">
                    <span>{{ row.productSn }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="{ row }">
                    <el-button
                      text
                      type="primary"
                      size="small"
                      @click="delShop(row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="备注：">
              <el-input
                style="width: 50%"
                v-model="form.note"
                type="textarea"
                placeholder="请输入内容"
                :autosize="{ minRows: 6, maxRows: 8 }"
              />
            </el-form-item>
          </div>
          <el-form-item>
            <template #default="{ row }">
              <el-button type="primary" @click="confirm">提交</el-button>
              <el-button @click="reset" v-show="!route.query.id"
                >重置</el-button
              >
            </template>
          </el-form-item>
        </el-form>
      </div></el-card
    >
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { add } from "lodash";
import { stringify } from "querystring";
import { reactive, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  addCouponApi,
  getCouponApi,
  getProductCategoryChildApi,
  getProductSimpleListApi,
  updateCouponApi,
} from "./api";
const locale = zhCn;
const formRef = ref<FormInstance>();
const loading = ref(false);
const route = useRoute();
const labelPosition = ref("right");
const type = ref("全场通用");
const router = useRouter();

const form = reactive<ICoupon>({
  type: 0,
  platform: 0,
  name: "",
  publishCount: 0,
  amount: 0,
  enableTime: "",
  startTime: "",
  endTime: "",
  useType: 0,
  note: "",
  perLimit: 0,
  minPoint: 0,
  code: "",
  count: 0,
  id: 0,
  memberLevel: 0,
  productCategoryRelationList: [],
  productRelationList: [],
  receiveCount: 0,
  useCount: 0,
});

// const form = ref<ICoupon[]>([]);

// 校验规则
var valiNumberPass2 = (rule: any, value: string, callback: any) => {
  //正整数
  let reg = /^[+]{0,1}(\d+)$/g;
  if (!reg.test(form.publishCount as unknown as string)) {
    callback(new Error("请正整数"));
  } else {
    callback();
  }
};
var validatePrice = (rule: any, value: string, callback: any) => {
  let reg = /^0\.([1-9]|\d[1-9])$|^[1-9]\d{0,8}\.\d{0,2}$|^[1-9]\d{0,8}$/;
  if (!reg.test(form.amount as unknown as string)) {
    callback(new Error("面值只能是数值，0.01-10000，限2位小数")); //防止输入多个小数点
  } else {
    callback();
  }
};

const rules = {
  name: [{ required: true, message: "请输入优惠券名称", trigger: "blur" }],
  publishCount: [
    { validator: valiNumberPass2, trigger: "blur", required: true },
  ],
  amount: [
    {
      require: true,
      validator: validatePrice,
      trigger: "blur",
      required: true,
    },
  ],
  perLimit: [{ validator: valiNumberPass2, trigger: "blur" }],
  minPoint: [{ validator: valiNumberPass2, trigger: "blur", required: true }],
};

const platformSelect = [
  {
    value: 0,
    label: "全平台",
  },
  {
    value: 1,
    label: "移动平台",
  },
  {
    value: 2,
    label: "PC平台",
  },
];
const option = [
  {
    value: 0,
    label: "全场赠券",
  },
  {
    value: 1,
    label: "会员赠券",
  },
  {
    value: 2,
    label: "购物赠券",
  },
  {
    value: 3,
    label: "注册赠券",
  },
];

// 选择可使用商品类型
const choseUseType = (value: any) => {
  console.log(value);
  if (value == "全场通用") {
    form.useType = 0;
    console.log(form.useType);
  } else if (value == "指定分类") {
    form.useType = 1;
    console.log(form.useType);
  } else {
    form.useType = 2;
    console.log(form.useType);
  }
};
const categoryList = ref<any>([]);
const userList = ref<ProductCategoryRelationList[]>([]);
// 获取指定分类
getProductCategoryChildApi().then((res) => {
  if (res.code === 200) {
    console.log(res.data);
    categoryList.value = res.data.map((item: IProductCategoryWithChildren) => ({
      value: item.name,
      label: item.name,
      children: item.children.map((item) => ({
        label: item.name,
        value: item.name,
        id: item.id,
      })),
    }));
    console.log(categoryList.value);
  }
});
const refSubCat = ref();
const addCategoryList = ref<any>({});
const handleChange = (value: any) => {
  // console.log(value);
  console.log(value);
  console.log(refSubCat.value.getCheckedNodes()[0].data);
  addCategoryList.value.id = refSubCat.value.getCheckedNodes()[0].data.id;
  addCategoryList.value.parentCategoryName = value[0];
  addCategoryList.value.productCategoryName = value[1];
  console.log(addCategoryList.value);
};
// 添加类型进表格
const addType = () => {
  if (!value) {
    ElMessage.warning("请选择商品");
  } else {
    userList.value.push(addCategoryList.value);
    console.log(userList.value);
    console.log(addCategoryList.value);
    value.value = "";
    addCategoryList.value = {};
  }
};
form.productCategoryRelationList = userList.value;
console.log(form);
// 删除分类的表格内容
const delCategory = (row: any) => {
  // console.log(id);
  const index = userList.value.findIndex((item) => item.id === row.id);
  userList.value.splice(index, 1);
  // shopList.value.splice
};
//模糊搜索指定商品
interface ListItem {
  value: number;
  label: string;
  productSn: string;
}
const value = ref("");
const addList = ref<any>({});
const list = ref<ListItem[]>([]);
const options = ref<ListItem[]>([]);
interface shop {
  id: number;
  productName: string;
  productSn: string;
}
const shopList = ref<ProductRelationList[]>([]);
const remoteMethod = (query: string) => {
  if (query) {
    console.log(query);
    loading.value = true;
    getProductSimpleListApi(query).then((res) => {
      if (res.code === 200) {
        console.log(res);
        list.value = res.data.map((item) => {
          return {
            value: item.id,
            label: item.name,
            productSn: item.productSn,
          };
        });
        setTimeout(() => {
          loading.value = false;
          options.value = list.value;
        }, 200);
      }
      console.log(list.value);
    });
  } else {
  }
};
// 当修改时的id的列表
const editList = ref<ProductRelationList[]>([]);
//添加指定商品
const addShop = () => {
  if (!value.value) {
    ElMessage.warning("请选择商品");
    console.log(shopList.value);
    console.log(value.value);
  } else {
    shopList.value.push(addList.value);
    console.log(addList.value);
    console.log(shopList.value);
    // form.productRelationList.push(addList.value);
    // Object.assign(form.productRelationList, shopList.value);
    // form.productRelationList.concat(addList.value);
    addList.value = {};
    value.value = "";
    console.log(addList.value, value.value);
  }
};
const handleSelectBranchCom = (item: any) => {
  console.log(item);
  addList.value.productName = item.label;
  addList.value.productSn = item.productSn;
  addList.value.productId = item.value;
  console.log(addList.value);
};
// 删除指定商品里的数据
const delShop = (row: any) => {
  // console.log(id);
  const index = shopList.value.findIndex((item) => item.id === row.id);
  shopList.value.splice(index, 1);
  // shopList.value.splice
};
console.log(addList.value);
form.productRelationList = shopList.value;
console.log(form);

const id = parseInt(route.query.id as string);
watch(
  () => id,
  () => {
    if (id) {
      if (form.useType == 0) {
        type.value = "全场通用";
      } else if (form.useType == 1) {
        type.value = "指定分类";
      } else {
        type.value = "指定商品";
      }
      console.log(type.value);
    }
  }
);
if (id) {
  getCouponApi(id).then((res) => {
    if (res.code === 200) {
      console.log(res.data);
      // form.type = res.data.type;
      // form.name = res.data.name;
      // form.platform = res.data.platform;
      // form.publishCount = res.data.publishCount;
      Object.assign(form, res.data);
      console.log(form.useType);
      form.useType = res.data.useType;
      shopList.value = res.data.productRelationList;
      editList.value = res.data.productRelationList;
      Object.assign(form.productRelationList, editList.value);
      // console.log(form);
      userList.value = res.data.productCategoryRelationList;
      if (form.useType == 0) {
        type.value = "全场通用";
      } else if (form.useType == 1) {
        type.value = "指定分类";
      } else {
        type.value = "指定商品";
      }
      console.log(type.value);
    }
  });
}
// 确定提交
const confirm = () => {
  // addConfirmList.value = form;
  formRef.value?.validate((ok: boolean) => {
    if (ok) {
      if (id) {
        ElMessageBox.confirm("确定修改吗？", "修改", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(() => {
            console.log(form);
            updateCouponApi(form).then((res) => {
              if (res.code === 200) {
                console.log(res);
                ElMessage.success("修改成功");
                formRef.value?.resetFields();
                router.push("/sms/coupon");
              }
            });
          })
          .catch(() => {
            ElMessage: "失败";
          });
      } else {
        console.log(form);
        ElMessageBox.confirm("确定修改吗？", "修改", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(() => {
            addCouponApi(form).then((res) => {
              if (res.code === 200) {
                console.log(res);
                ElMessage.success("添加成功");
                formRef.value?.resetFields();
                router.push("/sms/coupon");
              }
            });
          })
          .catch(() => {});
      }
    } else {
      ElMessage.error("失败");
    }
  });
};
// 重置
const reset = () => {
  ElMessage.success("重置成功");
  formRef.value?.resetFields();
};
</script>

<style lang="less" scoped>
.box {
  width: 65%;
  margin: 50px auto;
  .content {
    width: 80%;
    margin: 10px auto;
  }
}
.pro {
  float: right;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}
</style>
